  <template>
    <div class="dashboard-container">
      <!-- 欢迎信息 -->
      <!-- <h2 class="welcome-message">欢迎来到后台</h2> -->
      <h2 class="welcome-message">
      <span class="icon">👋</span> 
      <span class="text" style="background: linear-gradient(90deg, #40c4ff, #00aaff); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
        欢迎来到后台！期待您在这里找到更多乐趣和价值。🚀
      </span>
    </h2>
  
      <!-- 图表区域 -->
      <div class="chart-section">
        <p class="chart-caption">您最近活动的次数</p>
        <div ref="chartRef" :style="{ width: '100%', height: '500px' }"></div>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-section">
        <!-- 假设这里是你的表格组件 -->
        <table>
          <!-- 表格内容 -->
        </table>
        <!-- 期待语 -->
        <p class="expectation-message">
        <span class="icon">🌟</span> 
        <span class="text" style="color: #666; font-style: italic;">
          期待您参加更多的活动，一起创造更多精彩瞬间！✨
        </span>
      </p>
      </div>
    </div>
  </template>
  
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import { computed} from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from '../../../stores/user'
import { ActivityControllerService } from "../../../../generated/services/ActivityControllerService";
import type { ActivityMembershipQueryRequest, ActivityVO } from "../../../../generated";
import type { ECBasicOption } from 'echarts/types/dist/shared';
import { text } from 'stream/consumers';
// const activities = ref<ShowedActivity[]>([]);
const store = useUserStore();  // 使用 Pinia 的用户存储
const nowUserId = store.id;
const tableData = ref<ActivityVO[]>([]);      // 表格数据
const pageSize = ref(8);
const currentPage = ref(1);
//计算总数
const total = computed(() => tableData.value?.length||0);     
  const chartRef = ref(null);

onMounted(async () => {
  try {
    const response = await ActivityControllerService.listActivityVoOfUserByPage({
      userId: nowUserId,
      current: currentPage.value,
      pageSize: pageSize.value,
    } as ActivityMembershipQueryRequest);

    console.log('API Response:', response); // 打印响应数据以检查结构

    if (!response.data || !response.data.records) {
      throw new Error('Invalid response structure');
    }

    const activityList = response.data.records;

    // 生成最近六个月的完整时间轴
    const currentDate = new Date();
    const sixMonthsAgo = new Date();
    sixMonthsAgo.setMonth(currentDate.getMonth() - 6);

    const months: string[] = [];
    for (let i = 0; i <= 5; i++) {
      const date = new Date();
      date.setMonth(currentDate.getMonth() - (5 - i));
      const yearMonth = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      months.push(yearMonth);
    }

    // 初始化每月计数器
    const monthlyCounts: Record<string, number> = {};
    months.forEach(month => {
      monthlyCounts[month] = 0;
    });

    // 填充实际数据
    activityList.forEach(activity => {
      const date = new Date(activity.endTime as string);
      if (date >= sixMonthsAgo) {
        const yearMonth = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        if (monthlyCounts[yearMonth]) {
          monthlyCounts[yearMonth]++;
        } else {
          monthlyCounts[yearMonth] = 1;
        }
      }
    });

    const counts = months.map(month => monthlyCounts[month]);

    const chartInstance = echarts.init(chartRef.value);

    const option: Partial<ECBasicOption> = {
      color: ['#40c4ff', '#29d9d5', '#00aaff'],
      title: {
        // text: '每月活动参与次数',
        text: '最近六个月的活动参与情况',
        subtext: '数据来源于用户活动记录',
        left: 'center',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#333'
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(50,50,50,0.7)',
        textStyle: {
          color: '#fff'
        }
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLabel: {
          rotate: 45,
          margin: 20,
          color: '#666'
        },
        axisLine: {
          lineStyle: {
            color: '#ccc'
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#eee'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      series: [{
        name: '活动次数',
        type: 'bar',
        data: counts,
        barWidth: '60%',
        itemStyle: {
          borderRadius: 4,
          borderColor: 'rgba(0, 0, 0, 0.1)',
          borderWidth: 1,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#00bfff' },
              { offset: 1, color: '#0099cc' }
            ]
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 153, 204, 0.5)'
          }
        }
      }],
      grid: {
        left: '10%',
        right: '10%',
        bottom: '15%',
        top: '20%',
        containLabel: true
      },
      animationType: 'slide',
      animationEasing: 'elasticOut',
      animationDelay: (idx: number) => idx * 100
    };

    chartInstance.setOption(option);
  } catch (error) {
    console.error('Error fetching or processing activity data:', error);
    ElMessage.error('Failed to fetch activity data');
  }
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.welcome-message {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
  position: relative;
}

.welcome-message .icon {
  font-size: 28px;
  color: #40c4ff;
  margin-right: 10px;
}

.chart-section {
  width: 100%;
  margin-bottom: 20px;
}

.chart-caption {
  font-size: 18px;
  color: #666;
  margin-bottom: 10px;
  text-align: center;
}

.table-section {
  position: relative;
}

.expectation-message {
  font-size: 16px;
  color: #999;
  margin-top: 10px;
  text-align: center;
  position: relative;
}

.expectation-message .icon {
  font-size: 24px;
  color: #ffcc00;
  margin-right: 10px;
}

</style>
